# import json
# import flask
# server = flask.Flask(__name__)
# @server.route('/login')
# def login():
#    return 'hhahahahah'
# server.run(port=2345)


import flask,json,time
import hashlib
server = flask.Flask(__name__)           # 实例化server，把当前这个python文件当作一个服务，__name__代表当前这个python文件
@server.route('/index',methods=['get'])  # 'index'是接口路径，methods不写，则默认get请求
 # 装饰器，下面的函数变为一个接口
def index():
    # res = {'msg':'这是我开发的第一个接口','msg_code':'0000'}
    # res = 'SUCCESS'
    # time.sleep(2)
    # return res
    file = flask.request.values.get('file')
    file1 = open(r'%s'%file, 'rb')
    a = hashlib.md5(file1.read())
    # file.close()
    print(a.hexdigest())
    return a.hexdigest()
    # return json.dumps(res,ensure_ascii=False)
  # json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False

def my_db(sql):
    import pymysql
    coon = pymysql.connect(host='127.0.0.1', user='root', passwd='123456',port=3306, db='test', charset='utf8')
    cur = coon.cursor() #建立游标
    cur.execute(sql)#执行sql
    if sql.strip()[:6].upper()=='SELECT':
        res =  cur.fetchall()
    else:
        coon.commit()
        res = 'ok'
    cur.close()
    coon.close()
    return res

@server.route('/reg',methods=['get','post'])
def reg():#注册
    username =flask.request.values.get('username')
    pwd = flask.request.values.get('pwd')
    if username and pwd:
        sql = 'select * from my_user where username = "%s";'%username
        if my_db(sql):
            res = {'msg':'用户已存在','msg_code':2001}
            return json.dumps(res, ensure_ascii=False)
        else:
            insert_sql = 'insert into my_user(username,passwd) values ("%s","%s");'%(username,pwd)
            my_db(insert_sql)
            # res = {'msg':'注册成功','msg_code':1000}
            # res = {'msg':'regok','msg_code':1000}
            res = 'SUCCESS'
            # return json.dumps(res,ensure_ascii=False)
            return res
    else:
        res = {'msg':'必填字段未填，请查看接口文档！','msg_code':1001}
        return json.dumps(res,ensure_ascii=False)

server.run(port=8881,debug=True,host='0.0.0.0')  # 启动服务
# debug=True,改了代码后，不用重启，它会自动重启
# 'host='0.0.0.0'别人可以通过IP访问




if __name__ == '__main__':#直接打main就能快捷键出来
    pass